﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using Castle.Windsor;
using RuTracker.MVC.Core;
using RuTracker.MVC.Core.CustomAuth;
using RuTrackerLib;

namespace RuTracker.MVC
{
    public class MvcApplication : System.Web.HttpApplication, IContainerAccessor
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            //RouteDebuggerHttpModule module = new RouteDebuggerHttpModule();
            //module.Init(this);
            

            Log.Initialize();
            Container = Bootstrapper.BootstrapContainer();
            Core.Container.SetContainerAccessor(this);
        }

        protected void Application_End(object sender, EventArgs e)
        {
            if (Container != null)
            {
                Container.Dispose();
                Container = null;
            }
        }

        protected void Application_OnAuthenticateRequest(Object sender, EventArgs e)
        {
            AuthenticationRequestHandler.Handle(Context, Request);
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = Server.GetLastError();
            if (ex != null)
                Log.Error(ex);
        }

        public IWindsorContainer Container { get; private set; }
    }
}